package offer;

import java.util.HashMap;

public class offerII_0011 {
    public int findMaxLength(int[] nums) {
        int len=nums.length;
        int[] pre=new int[len+1];
        pre[0]=0;
        for(int i=1;i<len+1;++i){
            if(nums[i-1]==0) pre[i]=pre[i-1]-1;
            else pre[i]=pre[i-1]+nums[i-1];
        }
        int maxlen=0;
        HashMap<Integer, Integer> map=new HashMap<>();
        map.put(0,0);
        for(int i=1;i<len+1;++i){
            if(map.containsKey(pre[i])){
                maxlen=Math.max(maxlen,i-map.get(pre[i]));
            }
            else map.put(pre[i],i);
        }
        return maxlen;
    }
}
